package view;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class cardtest extends JPanel {
		
		/**
		 * 
		 */
		private static final long serialVersionUID = 9215336425517416421L;
		// This is information associated with a specific image file. 
		// Should be read from a property file.
		protected static final int WIDTH = 71; // Width of sub image
		protected static final int HEIGHT = 95; // Height of sub image

		private BufferedImage[] theImages = null;
		private ImageIcon cardIcon = null;
		private java.util.Random rand;

	    public cardtest() {
	    	this.setSize(400, 400);
	    	JButton pick = new JButton("Pick a card");
	    	this.add(pick);
	    	pick.addActionListener(
	    		new ActionListener() {
	    			public void actionPerformed(ActionEvent ae) {
	    				cardtest.this.showRandomCard();
	    			}
	    		}
	    	);
	    	this.setBackground(Color.green);
	   		this.intializeImages("Fancy.bmp");
	   		rand = new java.util.Random();
	    }
	    
	    protected void intializeImages(String file) {
	    	try {
	    		InputStream is = this.getClass().getClassLoader().getResourceAsStream(file);
		    	ImageInputStream iis = ImageIO.createImageInputStream(is);
				BufferedImage theCompleteImage = ImageIO.read(iis);
				theImages = new BufferedImage[52];
				int n = 0;
				for(int r = 0; r < 13; r++) {
					for(int s = 0; s < 4; s++) {
						theImages[n++] = theCompleteImage.getSubimage(r*WIDTH, s*HEIGHT, WIDTH, HEIGHT);
					}
				}
	    	}
	    	catch(IOException ie) {
	    		JOptionPane.showMessageDialog(this, "Error", "Couldn't create image buffer.", JOptionPane.ERROR_MESSAGE);
	    	}
	    }
	    
	    protected void showRandomCard() {
	    	int n = rand.nextInt(52);
	    	cardIcon = new ImageIcon(theImages[n]);
	    	repaint();
	    }
	    
	    public void paintComponent(Graphics g) {
	    	super.paintComponent(g);
	    	if(cardIcon != null) {
	    		cardIcon.paintIcon(this, g, (this.getWidth()-WIDTH)/2, (this.getHeight()-HEIGHT)/2);
	    	}
	    }
}
